/**
 * 创建邮件模板页面
 */
import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Switch,
  Divider,
  Alert,
  Tag,
  Tabs,
} from 'antd';
import { ArrowLeftOutlined, EyeOutlined, ApiOutlined, SaveOutlined } from '@ant-design/icons';
import EmailEditor, { insertVariableAtCursor } from '@/components/EmailEditor';
import SystemVariablePanel from '@/components/SystemVariablePanel';
import { history } from '@umijs/max';
import {
  createEmailTemplate,
  extractTemplateVariables,
  previewTemplate,
  type EmailTemplateCreate,
  type TemplateVariableExtractRequest,
  type TemplatePreviewRequest,
  TemplateType,
  TemplateCategory,
} from '@/services/emailTemplate';
import { getDataSources, type DataSourceItem } from '@/services/dataSource';
import { request } from '@umijs/max';

const { Option } = Select;
const { TextArea } = Input;
const { TabPane } = Tabs;

const CreateEmailTemplate: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [extractLoading, setExtractLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [extractedVariables, setExtractedVariables] = useState<string[]>([]);
  const [previewData, setPreviewData] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('edit');
  const [templateType, setTemplateType] = useState<TemplateType>(TemplateType.HTML);

  // 获取数据源列表
  const fetchDataSources = async () => {
    try {
      const response = await getDataSources({ page: 1, size: 100 });
      setDataSources(response.items);
    } catch (error) {
      console.error('获取数据源失败:', error);
    }
  };

  // 处理数据源选择（由EmailComposer组件处理）
  const handleDataSourceChange = (dataSource: DataSourceItem | null) => {
    setSelectedDataSource(dataSource);
  };

  // 初始化
  React.useEffect(() => {
    fetchDataSources();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values: EmailTemplateCreate) => {
    setLoading(true);
    try {
      await createEmailTemplate({
        ...values,
        subject: emailContent.subject,
        content: emailContent.content,
        variables: extractedVariables,
      });
      message.success('邮件模板创建成功');
      history.push('/templates');
    } catch (error: any) {
      message.error(error.message || '创建失败');
    } finally {
      setLoading(false);
    }
  };

  // 提取模板变量
  const handleExtractVariables = async () => {
    try {
      if (!emailContent.subject || !emailContent.content) {
        message.warning('请先填写模板内容和主题');
        return;
      }

      setExtractLoading(true);

      const extractData: TemplateVariableExtractRequest = {
        content: emailContent.content,
        subject: emailContent.subject,
      };

      const result = await extractTemplateVariables(extractData);
      setExtractedVariables(result.variables);
      message.success(`提取到 ${result.variables.length} 个变量`);
    } catch (error: any) {
      message.error(error.message || '变量提取失败');
    } finally {
      setExtractLoading(false);
    }
  };

  // 处理预览
  const handlePreview = (previewResult: any) => {
    setPreviewData(previewResult);
    setActiveTab('preview');
  };

  // 预设模板
  const presetTemplates = [
    {
      name: '欢迎邮件',
      category: TemplateCategory.WELCOME,
      subject: '欢迎加入 {{company_name}}！',
      content: `亲爱的 {{user_name}}，

欢迎加入 {{company_name}}！我们很高兴您成为我们大家庭的一员。

您的账户信息：
- 用户名：{{username}}
- 注册邮箱：{{email}}
- 注册时间：{{register_time}}

如果您有任何问题，请随时联系我们。

祝好！
{{company_name}} 团队`,
    },
    {
      name: '营销推广',
      category: TemplateCategory.MARKETING,
      subject: '{{product_name}} - 限时优惠，不容错过！',
      content: `亲爱的 {{customer_name}}，

我们为您带来了 {{product_name}} 的限时优惠活动！

🎉 优惠详情：
- 产品：{{product_name}}
- 原价：{{original_price}}
- 优惠价：{{discount_price}}
- 优惠截止：{{end_date}}

立即购买：{{purchase_link}}

感谢您的支持！`,
    },
  ];

  // 应用预设模板
  const applyPresetTemplate = (preset: any) => {
    form.setFieldsValue({
      name: preset.name,
      category: preset.category,
    });
    setEmailContent({
      subject: preset.subject,
      content: preset.content,
    });
    setExtractedVariables([]);
    setPreviewData(null);
    setActiveTab('edit');
  };

  return (
    <PageContainer
      header={{
        title: '创建邮件模板',
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/templates')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Card>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="编辑模板" key="edit">
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                template_type: TemplateType.HTML,
                category: TemplateCategory.CUSTOM,
                is_active: true,
              }}
            >
              {/* 预设模板快速选择 */}
              <Alert
                message="快速开始"
                description={
                  <div style={{ marginTop: 8 }}>
                    <Space wrap>
                      {presetTemplates.map((preset, index) => (
                        <Button
                          key={index}
                          size="small"
                          onClick={() => applyPresetTemplate(preset)}
                        >
                          {preset.name}
                        </Button>
                      ))}
                    </Space>
                  </div>
                }
                type="info"
                showIcon
                style={{ marginBottom: 24 }}
              />

              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    name="name"
                    label="模板名称"
                    rules={[
                      { required: true, message: '请输入模板名称' },
                      { min: 2, message: '模板名称至少需要2个字符' },
                    ]}
                  >
                    <Input placeholder="请输入模板名称" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name="description" label="模板描述">
                    <Input placeholder="请输入模板描述（可选）" />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={24}>
                <Col span={8}>
                  <Form.Item
                    name="category"
                    label="模板分类"
                    rules={[{ required: true, message: '请选择模板分类' }]}
                  >
                    <Select placeholder="请选择模板分类">
                      <Option value={TemplateCategory.MARKETING}>营销邮件</Option>
                      <Option value={TemplateCategory.NOTIFICATION}>通知邮件</Option>
                      <Option value={TemplateCategory.NEWSLETTER}>新闻邮件</Option>
                      <Option value={TemplateCategory.WELCOME}>欢迎邮件</Option>
                      <Option value={TemplateCategory.REMINDER}>提醒邮件</Option>
                      <Option value={TemplateCategory.CUSTOM}>自定义</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    name="template_type"
                    label="模板类型"
                    rules={[{ required: true, message: '请选择模板类型' }]}
                  >
                    <Select placeholder="请选择模板类型">
                      <Option value={TemplateType.HTML}>HTML</Option>
                      <Option value={TemplateType.MARKDOWN}>Markdown</Option>
                      <Option value={TemplateType.PLAIN_TEXT}>纯文本</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="is_active" label="启用状态" valuePropName="checked">
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                  </Form.Item>
                </Col>
              </Row>

              {/* 主要内容区域 - 左右分栏布局 */}
              <Row gutter={24}>
                {/* 左侧：模板编辑区域 */}
                <Col xs={24} lg={16}>
                  <Space direction="vertical" style={{ width: '100%' }} size="middle">
                    {/* 邮件编辑器 */}
                    <EmailEditor
                      form={form}
                      showSubject={true}
                      subjectLabel="邮件主题"
                      contentLabel="邮件内容"
                      subjectPlaceholder="请输入邮件主题，支持变量如：{{current_date}}"
                      contentPlaceholder="请输入邮件内容，支持HTML和变量，如：尊敬的用户，今天是{{current_date}}，祝您工作愉快！"
                      contentRows={15}
                      templateType={templateType}
                      showTemplateType={true}
                      onTemplateTypeChange={(type) => {
                        setTemplateType(type);
                        form.setFieldValue('template_type', type);
                      }}
                    />

                    {/* 变量提取结果 */}
                    {extractedVariables.length > 0 && (
                      <Card title="提取的变量" size="small">
                        <Space wrap>
                          {extractedVariables.map((variable, index) => (
                            <Tag key={index} color="blue">
                              {variable}
                            </Tag>
                          ))}
                        </Space>
                      </Card>
                    )}
                  </Space>
                </Col>

                {/* 右侧：系统变量面板 */}
                <Col xs={24} lg={8}>
                  <SystemVariablePanel
                    onVariableClick={(variableName) => {
                      insertVariableAtCursor(form, variableName);
                    }}
                    title="系统变量"
                  />
                </Col>
              </Row>



              {/* 操作按钮 */}
              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    htmlType="submit"
                    loading={loading}
                    size="large"
                  >
                    保存模板
                  </Button>

                  <Button
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                    loading={previewLoading}
                    size="large"
                  >
                    预览模板
                  </Button>

                  <Button
                    icon={<ApiOutlined />}
                    onClick={handleExtractVariables}
                    loading={extractLoading}
                    size="large"
                  >
                    提取变量
                  </Button>

                  <Button
                    icon={<ArrowLeftOutlined />}
                    onClick={() => history.push('/templates')}
                    size="large"
                  >
                    返回列表
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="预览效果" key="preview">
            {previewData ? (
              <div>
                <Card title="预览结果" style={{ marginBottom: 16 }}>
                  <div style={{ marginBottom: 16 }}>
                    <strong>渲染后的主题：</strong>
                    <div style={{ marginTop: 8, padding: 8, backgroundColor: '#f5f5f5' }}>
                      {previewData.rendered_subject}
                    </div>
                  </div>
                  
                  <div style={{ marginBottom: 16 }}>
                    <strong>HTML内容：</strong>
                    <div 
                      style={{ 
                        marginTop: 8, 
                        padding: 16, 
                        border: '1px solid #d9d9d9',
                        backgroundColor: '#fff',
                        minHeight: 200,
                      }}
                      dangerouslySetInnerHTML={{ __html: previewData.html_content }}
                    />
                  </div>

                  {previewData.variables_used.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <strong>使用的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.variables_used.map((variable: string, index: number) => (
                            <Tag key={index} color="green">
                              {variable}
                            </Tag>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}

                  {previewData.missing_variables.length > 0 && (
                    <div>
                      <strong>缺失的变量：</strong>
                      <div style={{ marginTop: 8 }}>
                        <Space wrap>
                          {previewData.missing_variables.map((variable: string, index: number) => (
                            <Tag key={index} color="red">
                              {variable}
                            </Tag>
                          ))}
                        </Space>
                      </div>
                    </div>
                  )}
                </Card>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: 50, color: '#999' }}>
                请先在编辑页面点击"预览模板"按钮生成预览
              </div>
            )}
          </TabPane>
        </Tabs>
      </Card>
    </PageContainer>
  );
};

export default CreateEmailTemplate;
